'use strict';
var fs = require('fs');

/*
  ##### 异步读取
  >fs.readFile('文件目录', '字符编码' , function(err, data))
  ##### 同步读取
  >fs.readFileSync('文件目录', '字符编码')
  ##### 字符串和 Buffer 对象互转
*/

fs.readFile('./2/fs/smpale.txt', 'utf-8', function(err, data){
  console.log('-------------')
  console.log('异步读取文件')
  if (err) {
    console.log(err)
  } else {
    console.log(data)
  }
})
console.log('-------------')
console.log('同步读取文件')
var syncReadNoe = fs.readFileSync('./2/fs/smpale.txt', 'utf-8')
console.log(syncReadNoe)
console.log('-------------')
console.log('字符串转 Buffe')
var str = 'aa2233bb'
str = Buffer.from(str, 'utf-8')
console.log(str)
console.log('-------------')
console.log('Buffer 转字符串')
var str = str.toString('utf-8')
console.log(str)

/*
  #### write
  ##### 异步写入
  >fs.writeFile('文件目录', '字符编码' , function(err, data))
  ##### 同步写入
  >fs.writeFileSync('文件目录', '字符编码')
*/
fs.writeFile('./2/fs/aa.tnt', 'sync write utf-8', function(err, data) {
  console.log('-------------')
  console.log('同步写入')
  if (err) {
    console.log(err)
  } else {
    console.log('ok.')
  }
})

try {
  let bufferWrite = Buffer.from('aabbb22aaaa', 'utf-8');
  console.log('-------------')
  console.log('同步写入 Buffer 对象')
  fs.writeFileSync('./2/fs/aa.txt', bufferWrite)
  console.log('ok')
} catch (e) {
  console.log(e)
}

fs.stat('./2/fs/100.png', function(err, stat) {
  console.log('-------------')
  console.log('异步获取文件状态')
  if (err) {
    console.log(err)
  } else {
    console.log('is File: ' + stat.isFile())
    console.log('is Directory: ' + stat.isDirectory())
    console.log('file size: ' + stat.size)
    console.log('birch time: ' + stat.birthtime)
    console.log('modified time: ' + stat.mtime)
    console.log(stat)
  }
})

console.log('-------------')
console.log('同步获取文件状态')
